package com.lq.dept.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

//数据库工具类
public class DBUtil {

    private static DataSource dataSource;

    //为了防止别人初始化这个类，构造函数私有化
    private DBUtil(){}

    static{//通过静态代码块给静态属性赋值
        //1.创建Properties对象
        Properties properties = new Properties();
        //2.创建输入流
        InputStream is= DBUtil.class.getClassLoader()
                .getResourceAsStream("druid.properties");
        //3.通过输入流，读取配置文件中的信息
        try {
            properties.load(is);//通过输入流读取文件
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得数据库连接
     * @return
     */
    public static Connection getConn() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭数据库连接
     *  connection preparedstatment  resulset
     */
    public static void close(Connection conn, PreparedStatement pst, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(pst!=null){
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
